<?php

namespace App\Api\Services;

use App\Api\Models\AdminModel;
use App\Api\Models\LogInStorageModel;
use App\Api\Models\LogOutStorageModel;
use App\Api\Models\LogPackageModel;
use App\Api\Models\ModuleModel;
use App\Api\Models\StorageBatchModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use JMessage\IM\Admin;

class AdminService
{
    const SALT = 'storage';

    //获取被邀请人信息
    static public function inviteInfo($bindId)
    {
        $arr = [];
        if($bindId != 0) {
            $bindUserInfo = AdminModel::select('mobile')
                ->where('bind_id', $bindId)
                ->limit(3)
                ->orderBy('id', 'DESC')
                ->get();

            foreach($bindUserInfo as $value) {
                $arr[] = $value['mobile'];
            }
        }

        return $arr;
    }

    //子账号列表
    static public function userList($mainId, $data)
    {
        return AdminModel::userList($mainId, $data);
    }

    //检查子账户是否存在
    static public function checkUser($id)
    {
        if(!empty(AdminModel::where('id', $id)->first())) {
            return true;
        }
        else {
            return false;
        }
    }

    //审批人列表
    static public function approverList($mainId)
    {
        return AdminModel::getApproverList($mainId);
    }

    //重置指定子账号登录密码
    static public function resetPwd($data)
    {
        $isUpdate = AdminModel::where('id', $data['id'])->update([
            'password' => md5(md5('123456'.SELF::SALT)),
            'is_default_pwd' => 0
        ]);

        if($isUpdate !== false) {
            return true;
        }
        else {
            return false;
        }
    }

    //检查子账号是否已存在
    static public function checUserInfo($mainId, $data)
    {
        $userInfo = AdminModel::where([
            'username' => $data['username'],
            'delete_flag' => 0
        ])
            ->where('parent_id', '!=', 0)
            ->first();

        if(empty($userInfo)) {
            return true;
        }
        else {
            return false;
        }
    }

    //新建子账号
    static public function addUser($mainId, $data)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        $data['parent_id'] = $mainId;
        $data['password'] = md5(md5('123456'.SELF::SALT));
        $data['company_name'] = empty($mainInfo['company_name'])?'':$mainInfo['company_name'];
        $data['company_class'] = $mainInfo['company_class'];
        $data['created_at'] = time();
        $data['is_active'] = $data['status'];
        unset($data['status']);

        $userId = AdminModel::insertGetId($data);

        return ['id' => $userId];
    }

    //获取子账号权限信息
    static public function getUserPermission($mainId, $userInfo)
    {
        $parentModuleInfo = SELF::parentModuleInfo($mainId);

        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

        // $moduleInfo = ModuleService::roleModuleList();

        $arr = [];
        foreach($parentModuleInfo as $key => $value)
        {
            $arr[$key]['id'] = $value['id'];
            $arr[$key]['module_name'] = $value['module_name'];
            $arr[$key]['type'] = $value['type'];
            $arr[$key]['sort'] = $value['sort'];
            $arr[$key]['module_img'] = empty($value['module_img'])?'':$value['module_img'];

            if(in_array($value['id'], $userFirstModuleArr)) {
                $arr[$key]['is_enable'] = 1;
            }
            else {
                $arr[$key]['is_enable'] = 0;
            }

            foreach($value['second_module'] as $k => $v) {
                $arr[$key]['second_module'][$k]['module_img'] = empty($v['module_img'])?'':$v['module_img'];
                if(in_array($v['id'], $userSecondModuleArr)) {
                    $arr[$key]['second_module'][$k]['is_enable'] = 1;
                }
                else {
                    $arr[$key]['second_module'][$k]['is_enable'] = 0;
                }

                $arr[$key]['second_module'][$k]['id'] = $v['id'];
                $arr[$key]['second_module'][$k]['module_name'] = $v['module_name'];
                $arr[$key]['second_module'][$k]['type'] = $v['type'];
                $arr[$key]['second_module'][$k]['sort'] = $v['sort'];
                $arr[$key]['second_module'][$k]['upper_module_id'] = $v['upper_module_id'];
            }
        }

        return $arr;
    }

    static private function parentModuleInfo($mainId)
    {
        $moduleInfo = AdminModel::select(
            'b.first_module',
            'b.second_module'
        )
            ->from('admin as a')
            ->leftJoin('role_setting as b', 'b.role_id', '=', 'a.admin_role')
            ->where('a.id', $mainId)->first();

        $firstModule = array_filter(explode(',', $moduleInfo['first_module']), function($v) { return $v !== ''; });
        $secondModule = array_filter(explode(',', $moduleInfo['second_module']), function($v) { return $v !== ''; });

        return ModuleModel::usefulPermission($firstModule, $secondModule);
    }

    //检查旧密码是否正确
    static public function checkPwd($userId, $data)
    {
        $userInfo = AdminModel::where('id', $userId)->first();

        if(md5(md5($data['old_pwd'].SELF::SALT)) != $userInfo['password']) {
            return false;
        }
        else {
            return true;
        }
    }

    //子账号修改登录密码
    static public function changePwd($userId, $data)
    {
        AdminModel::where('id', $userId)->update([
            'password' => md5(md5($data['new_pwd'].SELF::SALT)),
            'is_default_pwd' => 1
        ]);

        return true;
    }

    //个人中心
    static public function userCenter($userId, $mainId)
    {
        $data = AdminModel::select(
            'a.id',
            'username',
            'nickname',
            'mobile',
            'parent_id',
            'company_name',
            'company_class',
            'is_active',
            'bind_id',
            'invite_num',
            'b.name',
            'is_default_pwd',
            'openid as is_bind_openid',
            'wx_nickname',
            'out_storage_way',
            'batch_title'
        )
            ->from('admin as a')
            ->leftJoin('company_class as b', 'a.company_class', '=', 'b.id')
            ->where('a.id', $userId)->first();

        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        if($userId == $mainId) {
            $condition['main_id'] = ['EQ' => $mainId];
            unset($data['is_default_pwd']);
        }
        else {
            $condition['user_id'] = ['EQ' => $userId];
        }

        $mainInfo = AdminModel::where('id', $mainId)->first();

        $data['company_name'] = $mainInfo['company_name'];
        $data['parent_id'] = $mainId;
        $data['bind_id'] = $mainInfo['bind_id'];
        $data['invite_num'] = $mainInfo['invite_num'];
        $data['invite_info'] = SELF::inviteInfo($mainId);
        $data['is_bind_openid'] = empty($data['is_bind_openid'])?0:1;

        $data['today_in_storage'] = LogInstorageModel::getTodayInCount($condition, $startTime, $endTime);//今日入库总数
        $data['today_out_storage'] = LogOutStorageModel::getTodayOutCount($condition, $startTime, $endTime);//今日出库
        $data['today_package'] = LogPackageModel::getTodayPackageCount($condition, $startTime, $endTime);//今日套餐出库总数
        $data['today_trans_storage'] = LogOutstorageModel::getTodayAllocateCount($condition, $startTime, $endTime);//今日调拨数量

        return $data;
    }

    //查看被邀请人列表
    static public function inviteList($mainId, $data)
    {
        $result = AdminModel::select('nickname', 'mobile')->where('bind_id', $mainId)
            ->orderBy('id', 'DESC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $result;
    }

    static public function setPwd($data)
    {
        AdminModel::where('id', $data['id'])
            ->update([
                'password' => md5(md5($data['password'].SELF::SALT))
            ]);

        return true;
    }

    static public function transOutWay($mainId)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        DB::beginTransaction();

        try {
            //变更出库方式
            $updateData = [];
            if($mainInfo['out_storage_way'] == 0) {
                $updateData['out_storage_way'] = 1;
            }
            else {
                $updateData['out_storage_way'] = 0;
            }
            AdminModel::where('id', $mainId)->orWhere('parent_id', $mainId)->update($updateData);

            $storageBatchInfo = StorageBatchModel::select('id')
                ->where('batch_left_num', '!=', 0)
                ->where('main_id', $mainId)->get()->toArray();

            $time = time();
            foreach($storageBatchInfo as $value) {
                $batchNo = $mainInfo['batch_title'].date('YmdHis', $time).mt_rand(1000, 9999).'0';
                $checkBatchNo = StorageBatchModel::where('main_id', $mainId)
                    ->where('batch_no', $batchNo)->first();

                do {
                    $batchNo = $mainInfo['batch_title'].date('YmdHis', $time).mt_rand(1000, 9999).'0';
                }
                while(!empty($checkBatchNo));

                StorageBatchModel::where('id', $value['id'])
                    ->update([
                        'batch_no' => $batchNo
                    ]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('转换出库方式异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '转换失败,请重试', 'data' => ''];
        }
    }
}
